package com.xoa.controller.sso;

import com.google.gson.Gson;
import com.xoa.dao.casConfig.CasConfigMapper;
import com.xoa.dao.common.SysParaMapper;
import com.xoa.dao.sys.SysInterfaceMapper;
import com.xoa.dao.users.OrgManageMapper;
import com.xoa.dao.users.UserFunctionMapper;
import com.xoa.model.casConfig.CasConfig;
import com.xoa.model.common.SysPara;
import com.xoa.model.common.Syslog;
import com.xoa.model.sys.InterfaceModel;
import com.xoa.model.users.OrgManage;
import com.xoa.model.users.UserOnline;
import com.xoa.model.users.Users;
import com.xoa.model.worldnews.News;
import com.xoa.service.sys.SysLogService;
import com.xoa.service.users.UsersService;
import com.xoa.service.worldnews.NewService;
import com.xoa.util.*;
import com.xoa.util.common.StringUtils;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.dataSource.ContextHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.text.ParseException;
import java.util.*;

import static com.xoa.controller.login.loginController.userCountMap;

@Controller
public class PwegSsoController {

    @Autowired
    private OrgManageMapper orgManageMapper;

    @Resource
    private SysLogService sysLogService;

    @Resource
    private UsersService usersService;

    @Autowired
    private SysParaMapper sysParaMapper;

    @Autowired
    UserFunctionMapper userFunctionMapper;

    @Resource
    private CasConfigMapper casConfigMapper;

    @Resource
    private SysInterfaceMapper sysInterfaceMapper;
    @Resource
    private NewService newService;


    @RequestMapping(value = "/PwegSso/ssoLogin", produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public ToJson<Users> djssoLoginEnter(HttpServletRequest request, HttpServletResponse response) throws Exception {
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
        response.addHeader("Access-Control-Max-Age", "1800");//30 min
        Cookie redisSessionCookies = new Cookie("redisSessionId", request.getSession().getId());
        ToJson<Users> json = new ToJson<Users>(0, null);
        String YzmCode = request.getParameter("YzmCode");//前端传输的验证
        Long CurrTime = Long.valueOf(request.getParameter("CurrTime"));//前端传输的时间戳加一分钟
        //获取session中的验证码
        StringBuilder code = new StringBuilder();
        try {
            code = SessionUtils.getSessionInfo(request.getSession(), "yzm", StringBuilder.class, redisSessionCookies);
        } catch (Exception e) {
            json.setFlag(0);
            json.setMsg("请先获取验证码");
            return json;
        }
        Date date = new Date();
        long onemit = 60 * 1000;
        long time = date.getTime();//当前时间加一分钟后的时间
        if ((time - CurrTime) > onemit) {//判断是否超时,,一分钟
            json.setFlag(1);
            json.setMsg("验证码超时，请重新获取！");
            //将验证码设计为空
            SessionUtils.putSession(request.getSession(), "yzm", "", redisSessionCookies);
            return json;
        }
        if (!StringUtils.checkNull(YzmCode)&&!YzmCode.equals(code.toString())) {//判断验证码是否正确
            json.setFlag(1);
            //将验证码设计为空
            json.setMsg("验证码错误！");
            SessionUtils.putSession(request.getSession(), "yzm", "", redisSessionCookies);
            return json;
        }
        SessionUtils.putSession(request.getSession(), "yzm", "", redisSessionCookies);
        // 获取企业微信和钉钉登陆判断参数
        String thirdPartyType = request.getParameter("thirdPartyType");
        String loginId="1001";
        Integer h5Login=1;
        String password="temp";
        HttpSession session = request.getSession();
        String ssoUserName = request.getParameter("ByName");
        String loginUserId = (String) session.getAttribute("userId");
        String loginByName = (String) session.getAttribute("byname");
        boolean logBol = StringUtils.checkNull(loginUserId) ? false : true;
        boolean ssoBol = StringUtils.checkNull(ssoUserName) ? false : true;
        boolean byNameBol = StringUtils.checkNull(loginByName) ? false : true;
        if(logBol && ssoBol){
            if(ssoUserName.equals(loginByName)){
                byNameBol = true;
            }else{
                byNameBol = false;
            }
        }
        String targetUrl = "http://cfw.pweg.cn:1301/";
        //** 判断是否已经登录过 *//*
        if (logBol && byNameBol) {
            //如果登录,重定向到targetUrl
            response.sendRedirect(targetUrl+"main");
            //如果没有登陆过
        } else {
            //判断是否登录过
            if (ssoBol) {
                //** 写入单页面登录判断标志 *//*
                String username = ssoUserName;
                CookiesUtil.setCookie(response,"redisSessionId",request.getSession().getId());
                Cookie redisSessionCookie = new Cookie("redisSessionId",request.getSession().getId());
                if (StringUtils.checkNull(loginId)) {
                    List<OrgManage> org = orgManageMapper.queryId();
                    if (org != null && org.size() > 0) {
                        loginId = org.get(0).getOid().toString().trim();
                    }
                }
                if (StringUtils.checkNull(username)) {
                    json.setFlag(1);
                    json.setCode(LoginState.LOGINPASSWORDERR);
                    json.setMsg("用户名或用户不存在");
                    return json;
                }
                ContextHolder.setConsumerType("xoa" + loginId);
                Users user = usersService.selectUserAllInfoByName(username, request, loginId, password, h5Login,thirdPartyType);
                if (user == null) {
                    request.getSession().setAttribute("message", "errOne");
                    json.setMsg("用户名或用户不存在");
                    json.setCode(LoginState.LOGINPASSWORDERR);
                    json.setFlag(1);
                    return json;

                }

                List<SysPara> list = sysParaMapper.selectAll();
                String pd = "";
                String xts = "";
                String cz = "";
                for (SysPara sysPara : list) {
                    if ("SEC_RETRY_BAN".equals(sysPara.getParaName())) {
                        pd = sysPara.getParaValue();
                    }
                    if ("SEC_RETRY_TIMES".equals(sysPara.getParaName())) {
                        xts = sysPara.getParaValue();
                    }
                    if ("SEC_BAN_TIME".equals(sysPara.getParaName())) {
                        cz = sysPara.getParaValue();
                    }
                }

                Map<String, String> createMap = new HashMap<String, String>();
                createMap.put("userid", username);
                createMap.put("password", password);

                //获取当前用户的登录日志
                ToJson<Syslog> modifyPwdLog = sysLogService.getLoginLog(request);
                if(user.getLastVisitTime()!=null){
                    user.setLastVisitTime(new Date());
                    usersService.updateLoginTime(user);
                }else{
                    //判断他的size小于等于1，因为在查用户user信息时写入log日志的，因此第一次登录size为1
                    if (modifyPwdLog.getObj()==null||modifyPwdLog.getObj().size()<=1) {
                        json.setCode("FirstLogin");
                    } else {
                        user.setLastVisitTime(new Date());
                        usersService.updateLoginTime(user);
                    }
                }

                if (StringUtils.checkNull(loginId)) {
                    List<OrgManage> org = orgManageMapper.queryId();
                    if (org != null && org.size() > 0) {
                        loginId = org.get(0).getOid().toString().trim();
                    }
                }
                user.setCompanyId(loginId);
                //判断用户头像
                if(StringUtils.checkNull(user.getAvatar())){
                    if(!StringUtils.checkNull(user.getSex())){
                        user.setAvatar(user.getSex());
                    }else{
                        user.setAvatar("0");
                    }

                }else{
                    if(user.getAvatar().equals("0")||user.getAvatar().equals("1")){
                        if(!StringUtils.checkNull(user.getSex())){
                            user.setAvatar(user.getSex());
                        }else{
                            user.setAvatar("0");
                        }
                    }
                    else{
                        //判断用户头像是否找得到
                        String classpath = this.getClass().getResource("/").getPath();
                        String webappRoot = classpath.replaceAll("WEB-INF/classes/", "ui/img/user/");
                        File file_avtor =new File(webappRoot+user.getAvatar());
                        if(!file_avtor.exists()){
                            user.setAvatar(user.getSex());
                        }
                    }
                }
                json.setObject(user);
                json.setFlag(0);

                //通过userId查询用户是否存在于静态map中
                UserOnline userOnline = (UserOnline)userCountMap.get(user.getUserId());
                //如果不存在
                if(userOnline==null){
                    //声明一个新的用户在线数据
                    UserOnline userOnlineInfo =new UserOnline();
                    try {
                        String format = DateFormatUtils.formatDate(new Date());
                        Integer nowTime = DateFormatUtils.getNowDateTime(format);
                        userOnlineInfo.setClient((byte)2);
                        userOnlineInfo.setPCtime(nowTime);
                        userOnlineInfo.setPCsid(request.getSession().getId());
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                } else {//如果存在
                    if (!userOnline.getPCsid().equals("")) {
                        try {
                            String format = DateFormatUtils.formatDate(new Date());
                            Integer nowTime = DateFormatUtils.getNowDateTime(format);
                            userOnline.setPCtime(nowTime);
                            userCountMap.put(user.getUserId(), userOnline);
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                    } else {
                        try {
                            String format = DateFormatUtils.formatDate(new Date());
                            Integer nowTime = DateFormatUtils.getNowDateTime(format);
                            userOnline.setPCtime(nowTime);
                            userOnline.setPCsid(request.getSession().getId());
                            userCountMap.put(user.getUserId(), userOnline);
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                    }
                }

                Map<String, Object> params = new HashMap<String, Object>();
                params.put("paraName", "IM_WINDOW_CAPTION");
                params.put("paraValue", user.getPara().getParaValue());
                params.put("loginDateSouse", loginId);//组织id


                String functionIdStr = userFunctionMapper.getUserFuncIdStr(user.getUserId());
                params.put("functionIdStr", functionIdStr);

                List<InterfaceModel> interfaceModels = sysInterfaceMapper.getInterfaceInfo();
                if (0 == user.getTheme() || null == user.getTheme()) {
                    user.setTheme((byte) Integer.parseInt(interfaceModels.get(0).getTheme()));
                }

                String theme = "theme" + user.getTheme();
                params.put("InterfaceModel", theme);
                SessionUtils.putSession(request.getSession(), user,redisSessionCookie);
                SessionUtils.putSession(request.getSession(), params, redisSessionCookie);

                response.sendRedirect(targetUrl+"main");
            } else {
                CasConfig casConfig = casConfigMapper.selectOneCas();
                String sengUrl = "";
                if(casConfig != null  && StringUtils.checkNull(casConfig.getCasAddress())){
                    sengUrl = casConfig.getCasAddress();
                }
                //重定向到 获取登出地址
                response.sendRedirect(sengUrl);

            }
        }
        return null;
    }

    @RequestMapping(value = "/PwegYzm/YzmCode", produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public void YzmCode(@RequestParam("statuscallback") String callback, HttpServletRequest request, HttpServletResponse response) throws Exception {

        /*public String updateStatus(@RequestParam("statuscallback") String callback,String id){
            ServiceResult<String> result= EmplErrorService.updateStatus(id);
            return callback+"("+JSON.toJSONString(result)+")";
        }*/
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
        response.addHeader("Access-Control-Max-Age", "1800");//30 min
        ToJson json = new ToJson();
        String SecurityCode = request.getParameter("SecurityCode");
        StringBuilder str = new StringBuilder();//定义变长字符串
        if (SecurityCode.equals("ca857f3c-faea-5f8b-a1f4-a1976f826ae1")) {
            Random random = new Random();
            //随机生成数字，并添加到字符串
            for (int i = 0; i < 8; i++) {
                str.append(random.nextInt(10));
            }
            Date date = new Date();
            Cookie redisSessionCookie = new Cookie("redisSessionId", request.getSession().getId());
            SessionUtils.putSession(request.getSession(), "yzm", str, redisSessionCookie);
            json.setObject(str);
        } else {
            json.setObject("0");
        }
        json.setFlag(0);
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("json", json);
        //用回调函数名称包裹返回数据，这样，返回数据就作为回调函数的参数传回去了，callback()这个（）里面放的是json格式
        String returns = callback + "(" + new Gson().toJson(resultMap) + ")";
        response.getWriter().write(returns);
    }

    //新闻根据主键获取新闻的所有信息
    @RequestMapping(value = "/pwegNews/getOneById", method = RequestMethod.GET, produces = {"application/json;charset=UTF-8"})
    public @ResponseBody
    ToJson<News> queryNews(@RequestParam("newsId") Integer newsId) {
        ToJson<News> toJson = new ToJson<News>(0, "");
        try {
            News news = newService.getDataByNewsId(newsId,"xoa1001");
            toJson.setMsg("ok");
            toJson.setObject(news);
            return toJson;
        } catch (Exception e) {
            toJson.setMsg("err");
            return toJson;
        }
    }
}
